﻿namespace com.game.module.core
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using UnityEngine;

    public class CoroutineManager
    {
        private static CoroutineBehaviour behaviour;
        private static readonly List<Task> taskList = new List<Task>();

        public static void PauseAllCoroutine()
        {
            foreach (Task task in taskList)
            {
                task.Pause();
            }
        }

        public static void PauseCoroutine(Task t)
        {
            if (taskList.Contains(t))
            {
                t.Pause();
            }
        }

        public static void ResumeAllCoroutine()
        {
            foreach (Task task in taskList)
            {
                task.Unpause();
            }
        }

        public static void ResumeCoroutine(Task t)
        {
            if (taskList.Contains(t))
            {
                t.Unpause();
            }
        }

        public static Task StartCoroutine(IEnumerator routine, bool autoStart = true)
        {
            Task item = new Task(routine, autoStart);
            taskList.Add(item);
            return item;
        }

        public static Coroutine StartCoroutine(string methodName, object value = null)
        {
            if (behaviour == null)
            {
                GameObject target = new GameObject("CoroutineManager");
                UnityEngine.Object.DontDestroyOnLoad(target);
                behaviour = target.AddComponent<CoroutineBehaviour>();
            }
            return behaviour.StartCoroutine(methodName, value);
        }

        public static void StopAllCoroutine()
        {
            foreach (Task task in taskList)
            {
                task.Stop();
            }
            taskList.Clear();
        }

        public static void StopCoroutine(Task t)
        {
            if (taskList.Contains(t))
            {
                t.Stop();
                taskList.Remove(t);
            }
        }

        public static void StopCoroutine(string methodName)
        {
            if (behaviour != null)
            {
                behaviour.StopCoroutine(methodName);
            }
        }
    }
}

